﻿using System;
using System.Windows.Forms;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using tom;

namespace Company.PackageExtjs
{
    using System.Collections.Generic;
    using System.Drawing;
    using System.Linq;

    using Company.PackageExtjs.ColorItem;
    using Company.PackageExtjs.Intellisense;

    public partial class MyEditor1 : UserControl
    {
        private System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();

        private bool changeFlag;

        private const int GetOleInterfaceCommandId = 1084;

        private string m_TextToRecord;
        private VSMacroRecorder m_Recorder;

        private ColorItemDescriptionList ColorItemDescriptionList = new ColorItemDescriptionList();

        public MyEditor1()
        {
            InitializeComponent();
            //this.richTextBoxCtrl.WordWrap = false;
            //this.richTextBoxCtrl.HideSelection = false;
            
            m_Recorder = new VSMacroRecorder(GuidList.guidPackageExtjsEditorFactory);
        }

        public FastColoredTextBoxNS.FastColoredTextBox RichTextBoxControl
        {
            get
            {
                return this.fastColoredTextBox1;
            }
        }

        #region Fields

        /// <summary>
        /// This value is used internally so that we know what to display on the status bar.
        /// NOTE: Setting this value will not actually change the insert/overwrite behavior
        /// of the editor, it is just used so that we can keep track of the state internally.
        /// </summary>
        private bool overstrike;
        public bool Overstrike
        {
            get
            {
                return this.overstrike;
            }
            set
            {
                this.overstrike = value;
            }
        }

        private ITextDocument textDocument;

        /// <summary>
        /// This property exposes the ITextDocument interface associated with
        /// our Rich Text editor.
        /// </summary>
        public ITextDocument TextDocument
        {
            [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            get
            {
                if (null != textDocument)
                    return textDocument;

                // To get the IRichEditOle interface we need to call SendMessage, which
                // we imported from user32.dll
                object editOle = null;
                NativeMethods.SendMessage(fastColoredTextBox1.Handle,                // The rich text box handle
                                          GetOleInterfaceCommandId,   // The command ID for EM_GETOLEINTERFACE
                                          IntPtr.Zero,                // null
                                          out editOle                 // This will be set to the IRichEditOle interface
                                          );

                // Call GetIUnknownForObject with the IRichEditOle interface that we
                // just got so that we have an IntPtr to pass into QueryInterface
                IntPtr editOlePtr = IntPtr.Zero;
                editOlePtr = Marshal.GetIUnknownForObject(editOle);

                // Call QueryInterface to get the pointer to the ITextDocument
                IntPtr iTextDocument = IntPtr.Zero;
                Guid iTextDocumentGuid = typeof(ITextDocument).GUID;
                Marshal.QueryInterface(editOlePtr, ref iTextDocumentGuid, out iTextDocument);

                // We need to call Marshal.Release with the pointer that we got
                // from the GetIUnknownForObject call
                Marshal.Release(editOlePtr);

                // Call GetObjectForIUnknown passing in the pointer that was set
                // by QueryInterface and return it as an ITextDocument
                textDocument = Marshal.GetObjectForIUnknown(iTextDocument) as ITextDocument;
                return textDocument;
            }
        }

        /// <summary>
        /// This property will return the current ITextRange interface.
        /// </summary>
        public ITextRange TextRange
        {
            get
            {
                return this.TextDocument.Range(0, (int)tom.tomConstants.tomForward);
            }
        }

        /// <summary>
        /// This property will return the current ITextSelection interface.
        /// </summary>
        public ITextSelection TextSelection
        {
            get
            {
                return this.TextDocument.Selection;
            }
        }

        #endregion

        /// <summary>
        /// Returns the column number from the specified index
        /// </summary>
        /// <param name="index">index of the character</param>
        /// <returns>column number</returns>
        public int GetColumnFromIndex(int index)
        {
            //first get the index of the first char of the current line            
            //int currentLineIndex = fastColoredTextBox1.GetFirstCharIndexOfCurrentLine();
            //return index - currentLineIndex;
            return fastColoredTextBox1.GetColumnFromIndex(index);
        }

        /// <summary>
        /// Returns the index from the specified line and column number
        /// </summary>
        /// <param name="line">line number</param>
        /// <param name="column">column number</param>
        /// <returns>index</returns>
        public int GetIndexFromLineAndColumn(int line, int column)
        {
            if (line < 0)
                return -1;
            //first get the index of the first char of the specified line
            int firstCharLineIndex = fastColoredTextBox1.GetFirstCharIndexFromLine(line);
            if (firstCharLineIndex < 0)
                return -1;

            return firstCharLineIndex + column;
        }

        #region Macro Recording methods
        public void RecordDelete(bool backspace, bool word)
        {
            // If not backspace then it's a delete
            // If not word then it's a single character
            LastMacro macroType = backspace ?
                    (word ? LastMacro.BackspaceWord : LastMacro.BackspaceChar) :
                    (word ? LastMacro.DeleteWord : LastMacro.DeleteChar);

            // Get the number of times the macro type calculated above has been recorded already
            // (if any) and then add one to get the current count
            uint count = m_Recorder.GetTimesPreviouslyRecorded(macroType) + 1;

            string macroString = "";
            // if this parameter is negative, it indicates a backspace, rather then a delete
            macroString += "ActiveDocument.Object.Delete(" + (int)(word ? tom.tomConstants.tomWord : tom.tomConstants.tomCharacter) + ", " + (backspace ? -1 * count : count) + ")";

            m_Recorder.RecordBatchedLine(macroType, macroString);
        }

        public void RecordMove(LastMacro state, string direction, MoveScope scope, bool extend)
        {

            string macroString = "";
            macroString += "ActiveDocument.Object.Move";
            macroString += direction;
            // Get the number of times this macro type has been recorded already
            // (if any) and then add one to get the current count
            macroString += "(" + (int)scope + ", " + (m_Recorder.GetTimesPreviouslyRecorded(state) + 1) + ", " + (int)(extend ? tom.tomConstants.tomExtend : tom.tomConstants.tomMove) + ")";

            m_Recorder.RecordBatchedLine(state, macroString);
        }

        public void RecordCommand(string command)
        {
            if (m_Recorder.IsRecording())
            {
                string line = "ActiveDocument.Object.";

                line += command;

                m_Recorder.RecordLine(line);
            }
        }
        
        public void StopRecorder()
        {
            m_Recorder.Stop();
        }

        public void RecordPrintableChar(char currentValue)
        {
            string macroString = "";

            if (!m_Recorder.IsLastRecordedMacro(LastMacro.Text))
            {
                m_TextToRecord = "";
            }

            // Only deal with text characters.  Everything, space and above is a text character
            // except DEL (0x7f).  Include carriage return (enter key) and tab, which are
            // below space, since those are also text characters.
            if (char.IsLetterOrDigit(currentValue) ||
                    char.IsPunctuation(currentValue) ||
                    char.IsSeparator(currentValue) ||
                    char.IsSymbol(currentValue) ||
                    char.IsWhiteSpace(currentValue) ||
                    '\r' == currentValue || '\t' == currentValue)
            {
                if ('\r' == currentValue)
                {
                    // Emit "\r\n" as the standard line terminator
                    m_TextToRecord += "\" & vbCr & \"";
                }
                else if ('\t' == currentValue)
                {
                    // Emit "\t" as the standard tab
                    m_TextToRecord += "\" & vbTab & \"";
                }
                else
                {
                    m_TextToRecord += currentValue;
                }

                macroString += "ActiveDocument.Object.TypeText(\"";
                macroString += m_TextToRecord;
                macroString += "\")";

                if (m_Recorder.RecordBatchedLine(LastMacro.Text, macroString, 100)) // arbitrary max length
                {
                    // Clear out the buffer if the line hit max length, since
                    // it will not continue to be appended to
                    m_TextToRecord = "";
                }
            }       
        }
        
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        public void RecordNonprintableChar(Keys currentKey)
        {
            string macroString = "";

            // Obtain the CTRL and SHIFT as they modify a number of the virtual keys. 
            bool shiftDown = System.Windows.Forms.Keys.Shift == (System.Windows.Forms.Control.ModifierKeys & System.Windows.Forms.Keys.Shift); //Keyboard::IsKeyDown(VK_SHIFT);
            bool controlDown = System.Windows.Forms.Keys.Control == (System.Windows.Forms.Control.ModifierKeys & System.Windows.Forms.Keys.Control); //Keyboard::IsKeyDown(VK_CONTROL);

            // msg.WParam indicates the virtual key.
            switch (currentKey)
            {
                case Keys.Back: // BackSpace key
                    // Note that SHIFT does not affect this command
                    RecordDelete(true, controlDown);
                    break;

                case Keys.Delete:
                    // Note that SHIFT completely disables this command
                    if (!shiftDown)
                    {
                        RecordDelete(false, controlDown);
                    }
                    break;

                case Keys.Left: // Left Arrow
                    // SHIFT indicates selection, CTRL indicates words instead of characters
                    {
                        LastMacro macroType = controlDown ?
                        (shiftDown ? LastMacro.LeftArrowWordSelection : LastMacro.LeftArrowWord) :
                        (shiftDown ? LastMacro.LeftArrowCharSelection : LastMacro.LeftArrowChar);

                        RecordMove(macroType, "Left", controlDown ? MoveScope.Word : MoveScope.Character, shiftDown);
                    }
                    break;

                case Keys.Right: // Right Arrow
                    // SHIFT indicates selection, CTRL indicates words instead of characters
                    {
                        LastMacro macroType = controlDown ?
                        (shiftDown ? LastMacro.RightArrowWordSelection : LastMacro.RightArrowWord) :
                        (shiftDown ? LastMacro.RightArrowCharSelection : LastMacro.RightArrowChar);

                        RecordMove(macroType, "Right", controlDown ? MoveScope.Word : MoveScope.Character, shiftDown);
                    }
                    break;

                case Keys.Up: // Up Arrow
                    // SHIFT indicates selection, CTRL indicates paragraphs instead of lines
                    {
                        LastMacro macroType = controlDown ?
                        (shiftDown ? LastMacro.UpArrowParaSelection : LastMacro.UpArrowPara) :
                        (shiftDown ? LastMacro.UpArrowLineSelection : LastMacro.UpArrowLine);

                        RecordMove(macroType, "Up", controlDown ? MoveScope.Paragraph : MoveScope.Line, shiftDown);
                    }
                    break;

                case Keys.Down: // Down Arrow
                    // SHIFT indicates selection, CTRL indicates paragraphs instead of lines
                    {
                        LastMacro macroType = controlDown ?
                        (shiftDown ? LastMacro.DownArrowParaSelection : LastMacro.DownArrowPara) :
                        (shiftDown ? LastMacro.DownArrowLineSelection : LastMacro.DownArrowLine);

                        RecordMove(macroType, "Down", controlDown ? MoveScope.Paragraph : MoveScope.Line, shiftDown);
                    }
                    break;

                case Keys.Prior: // Page Up
                case Keys.Next: // Page Down
                    macroString += "ActiveDocument.Object.Move";

                    if (System.Windows.Forms.Keys.Prior == currentKey)
                    {
                        macroString += "Up";
                    }
                    else
                    {
                        macroString += "Down";
                    }

                    macroString += "(" + (int)(controlDown ? tom.tomConstants.tomWindow : tom.tomConstants.tomScreen) + ", 1, " + (int)(shiftDown ? tom.tomConstants.tomExtend : tom.tomConstants.tomMove) + ")";

                    m_Recorder.RecordLine(macroString);
                    break;

                case Keys.End:
                case Keys.Home:
                    macroString += "ActiveDocument.Object.";

                    if (System.Windows.Forms.Keys.End == currentKey)
                    {
                        macroString += "EndKey";
                    }
                    else
                    {
                        macroString += "HomeKey";
                    }

                    macroString += "(" + (int)(controlDown ? tom.tomConstants.tomStory : tom.tomConstants.tomLine) + ", " + (int)(shiftDown ? tom.tomConstants.tomExtend : tom.tomConstants.tomMove) + ")";

                    m_Recorder.RecordLine(macroString);
                    break;

                case Keys.Insert:
                    // Note that the CTRL completely disables this command.  Also the SHIFT+INSERT
                    // actually generates a WM_PASTE message rather than a WM_KEYDOWN
                    if (!controlDown)
                    {
                        macroString = "ActiveDocument.Object.Flags = ActiveDocument.Object.Flags Xor ";
                        macroString += (int)tom.tomConstants.tomSelOvertype;
                        m_Recorder.RecordLine(macroString);
                    }
                    break;
            }
        }

        // This event returns the literal key that was pressed and does not account for
        // case of characters.  KeyPress is used to handled printable characters.
        private void richTextBoxCtrl_KeyDown(object sender, KeyEventArgs e)
        {
            
            if (m_Recorder.IsRecording())
            {
                RecordNonprintableChar(e.KeyCode);
            }
        }

        // The arguments of this event will give us the char value of the key press taking into
        // account other characters press such as shift or caps lock for proper casing.
        private void richTextBoxCtrl_KeyPress(object sender, KeyPressEventArgs e)
        {            
            if (m_Recorder.IsRecording())
            {
                
                RecordPrintableChar(e.KeyChar);
            }
        }
        #endregion

        /*private bool populateListBox()
        {
            bool result = false;
            string word = this.getLastWord();

            //System.Diagnostics.Debug.WriteLine(" - Path: " +word);

            if (word != "")
            {
                findNodeResult = null;
                findNode(word, this.treeViewItems.Nodes);

                if (this.findNodeResult != null)
                {
                    this.listBoxAutoComplete.Items.Clear();

                    if (this.findNodeResult.Nodes.Count > 0)
                    {
                        result = true;

                        // Sort alphabetically (this could be replaced with
                        // a sortable treeview)
                        MemberItem[] items = new MemberItem[this.findNodeResult.Nodes.Count];
                        for (int n = 0; n < this.findNodeResult.Nodes.Count; n++)
                        {
                            MemberItem memberItem = new MemberItem();
                            memberItem.DisplayText = this.findNodeResult.Nodes[n].Text;
                            memberItem.Tag = this.findNodeResult.Nodes[n].Tag;

                            if (this.findNodeResult.Nodes[n].Tag != null)
                            {
                                System.Diagnostics.Debug.WriteLine(this.findNodeResult.Nodes[n].Tag.GetType().ToString());
                            }

                            items[n] = memberItem;
                        }
                        Array.Sort(items);

                        for (int n = 0; n < items.Length; n++)
                        {
                            int imageindex = 0;

                            if (items[n].Tag != null)
                            {
                                // Default to method (contains text for parameters)
                                imageindex = 2;
                                if (items[n].Tag is MemberTypes)
                                {
                                    MemberTypes memberType = (MemberTypes)items[n].Tag;

                                    switch (memberType)
                                    {
                                        case MemberTypes.Custom:
                                            imageindex = 1;
                                            break;
                                        case MemberTypes.Property:
                                            imageindex = 3;
                                            break;
                                        case MemberTypes.Event:
                                            imageindex = 4;
                                            break;
                                    }
                                }
                            }

                            this.listBoxAutoComplete.Items.Add(new GListBoxItem(items[n].DisplayText, imageindex));
                        }
                    }
                }
            }

            return result;
        }*/

        private bool populateListBox()
        {
            //this.listBoxAutoComplete.Items.Add(new PropositionListItem(items[n].DisplayText, imageindex));
            this.listBoxAutoComplete.Items.Add(new PropositionListItem("aaaa", 2));
            return true;
        }

        /* TB koment private void richTextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            int i = this.fastColoredTextBox1.SelectionStart;
            if (i >= 0)
            {
                var line = this.fastColoredTextBox1.GetLineFromCharIndex(i);
                var positionInLine = i - this.fastColoredTextBox1.GetFirstCharIndexFromLine(line);

                this.statusBar1.Text = string.Format("{0}, {1}", line, positionInLine);
            }
        }*/

        //private void richTextBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        //{
        //    // Keep track of the current character, used
        //    // for tracking whether to hide the list of members,
        //    // when the delete button is pressed
        //    int i = this.richTextBoxCtrl.SelectionStart;
        //    string currentChar = "";

        //    if (i > 0)
        //    {
        //        currentChar = this.richTextBoxCtrl.Text.Substring(i - 1, 1);
        //    }

        //    if (e.KeyData == Keys.OemPeriod)
        //    {
        //        // The amazing dot key

        //        if (!this.listBoxAutoComplete.Visible)
        //        {
        //            // Display the member listview if there are
        //            // items in it
        //            if (populateListBox())
        //            {
        //                //this.listBoxAutoComplete.SelectedIndex = 0;

        //                // Find the position of the caret
        //                Point point = this.richTextBoxCtrl.GetPositionFromCharIndex(richTextBoxCtrl.SelectionStart);
        //                point.Y += (int)Math.Ceiling(this.richTextBoxCtrl.Font.GetHeight()) + 2;
        //                point.X += 2; // for Courier, may need a better method
                        
        //                //this.statusBar1.Text = point.X + "," + point.Y;
        //                this.listBoxAutoComplete.Location = point;
        //                this.listBoxAutoComplete.BringToFront();
        //                this.listBoxAutoComplete.Show();
        //            }
        //        }
        //        else
        //        {
        //            this.listBoxAutoComplete.Hide();
        //            typed = "";
        //        }

        //    }
        //    else if (e.KeyCode == Keys.Back)
        //    {
        //        // Delete key - hides the member list if the character
        //        // being deleted is a dot

        //        this.textBoxTooltip.Hide();
        //        if (typed.Length > 0)
        //        {
        //            typed = typed.Substring(0, typed.Length - 1);
        //        }
        //        if (currentChar == ".")
        //        {
        //            this.listBoxAutoComplete.Hide();
        //        }

        //    }
        //    else if (e.KeyCode == Keys.Up)
        //    {
        //        // The up key moves up our member list, if
        //        // the list is visible

        //        this.textBoxTooltip.Hide();

        //        if (this.listBoxAutoComplete.Visible)
        //        {
        //            this.wordMatched = true;
        //            if (this.listBoxAutoComplete.SelectedIndex > 0)
        //                this.listBoxAutoComplete.SelectedIndex--;

        //            e.Handled = true;
        //        }
        //    }
        //    else if (e.KeyCode == Keys.Down)
        //    {
        //        // The up key moves down our member list, if
        //        // the list is visible

        //        this.textBoxTooltip.Hide();

        //        if (this.listBoxAutoComplete.Visible)
        //        {
        //            this.wordMatched = true;
        //            if (this.listBoxAutoComplete.SelectedIndex < this.listBoxAutoComplete.Items.Count - 1)
        //                this.listBoxAutoComplete.SelectedIndex++;

        //            e.Handled = true;
        //        }
        //    }
        //    /*else if (e.KeyCode == Keys.D9)
        //    {
        //        // Trap the open bracket key, displaying a cheap and
        //        // cheerful tooltip if the word just typed is in our tree
        //        // (the parameters are stored in the tag property of the node)

        //        string word = this.getLastWord();
        //        this.foundNode = false;
        //        this.nameSpaceNode = null;

        //        this.currentPath = "";
        //        searchTree(this.treeViewItems.Nodes, word, true);

        //        if (this.nameSpaceNode != null)
        //        {
        //            if (this.nameSpaceNode.Tag is string)
        //            {
        //                this.textBoxTooltip.Text = (string)this.nameSpaceNode.Tag;

        //                Point point = this.richTextBoxCtrl.GetPositionFromCharIndex(richTextBoxCtrl.SelectionStart);
        //                point.Y += (int)Math.Ceiling(this.richTextBoxCtrl.Font.GetHeight()) + 2;
        //                point.X -= 10;
        //                this.textBoxTooltip.Location = point;
        //                this.textBoxTooltip.Width = this.textBoxTooltip.Text.Length * 6;

        //                this.textBoxTooltip.Size = new Size(this.textBoxTooltip.Text.Length * 6, this.textBoxTooltip.Height);

        //                // Resize tooltip for long parameters
        //                // (doesn't wrap text nicely)
        //                if (this.textBoxTooltip.Width > 300)
        //                {
        //                    this.textBoxTooltip.Width = 300;
        //                    int height = 0;
        //                    height = this.textBoxTooltip.Text.Length / 50;
        //                    this.textBoxTooltip.Height = height * 15;
        //                }
        //                this.textBoxTooltip.Show();
        //            }
        //        }
        //    }*/
        //    else if (e.KeyCode == Keys.D8)
        //    {
        //        // Close bracket key, hide the tooltip textbox

        //        this.textBoxTooltip.Hide();
        //    }
        //    else if (e.KeyValue < 48 || (e.KeyValue >= 58 && e.KeyValue <= 64) || (e.KeyValue >= 91 && e.KeyValue <= 96) || e.KeyValue > 122)
        //    {
        //        // Check for any non alphanumerical key, hiding
        //        // member list box if it's visible.

        //        if (this.listBoxAutoComplete.Visible)
        //        {
        //            // Check for keys for autofilling (return,tab,space)
        //            // and autocomplete the richtextbox when they're pressed.
        //            if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Space)
        //            {
        //                this.textBoxTooltip.Hide();

        //                // Autocomplete
        //                this.selectItem();

        //                this.typed = "";
        //                this.wordMatched = false;
        //                e.Handled = true;
        //            }

        //            // Hide the member list view
        //            this.listBoxAutoComplete.Hide();
        //        }
        //    }
        //    else
        //    {
        //        // Letter or number typed, search for it in the listview
        //        if (this.listBoxAutoComplete.Visible)
        //        {
        //            char val = (char)e.KeyValue;
        //            this.typed += val;

        //            this.wordMatched = false;

        //            // Loop through all the items in the listview, looking
        //            // for one that starts with the letters typed
        //            for (i = 0; i < this.listBoxAutoComplete.Items.Count; i++)
        //            {
        //                if (this.listBoxAutoComplete.Items[i].ToString().ToLower().StartsWith(this.typed.ToLower()))
        //                {
        //                    this.wordMatched = true;
        //                    this.listBoxAutoComplete.SelectedIndex = i;
        //                    break;
        //                }
        //            }
        //        }
        //        else
        //        {
        //            this.typed = "";
        //        }
        //    }
        //}

        private void richTextBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // Hide the listview and the tooltip   
            this.textBoxTooltip.Hide();
            this.listBoxAutoComplete.Hide();
        }

        //private void richTextBoxCtrl_MouseEnter(object sender, EventArgs e)
        //{
        //    if(m_Recorder.IsRecording())
        //        richTextBoxCtrl.FilterMouseClickMessages = true;
        //    else
        //        richTextBoxCtrl.FilterMouseClickMessages = false;
        //}

        private void SetNodeColor(IEnumerable<Irony.Parsing.ParseTreeNode> nodeForColorList)
        {
            foreach (var colorTreeNode in nodeForColorList)
            {
                var loca = colorTreeNode.Span;
                var len = loca.Length;
                var x = loca.EndPosition;
                rtBox.Select(x - len, len);
                rtBox.SelectionColor = ColorItemDescriptionList.GetColor(colorTreeNode);
            }
            /*var loca = node.Span;
            //var comPos = loca.Location.Position;
            //var line = loca.Location.Line;
            var len = loca.Length;
            var x = loca.EndPosition;
            rtBox.Select(x - len, len);            
            switch (node.Term.Name)
            {
                case "Comment":
                    rtBox.SelectionColor = Color.Green;
                    break;
            }

            foreach (var child in node.ChildNodes)
            {
                this.SetTerminalColor();
            }*/
            
        }

        private List<Irony.Parsing.ParseTreeNode> PreapreLeafNodList(Irony.Parsing.ParseTreeNode node)
        {
            var leafList = new List<Irony.Parsing.ParseTreeNode>();
            var forAnalyze = new List<Irony.Parsing.ParseTreeNode> { node };
            var childForAnalyze = new List<Irony.Parsing.ParseTreeNode>();
            while (forAnalyze.Any())
            {
                foreach (var currentAnalyzeNode in forAnalyze)
                {
                    if (currentAnalyzeNode.ChildNodes.Any())
                    {
                        childForAnalyze.AddRange(currentAnalyzeNode.ChildNodes);
                        leafList.Add(currentAnalyzeNode);
                    }
                    else
                    {
                        leafList.Add(currentAnalyzeNode);
                    }
                }
                forAnalyze.RemoveAll(p => true);
                forAnalyze.AddRange(childForAnalyze);
                childForAnalyze.RemoveAll(p => true);
            }

            return leafList;
        }

        private void SetColors(Irony.Parsing.ParseTree parseTree)
        {
            var leafNodeList = PreapreLeafNodList(parseTree.Root.ChildNodes[0]);
            SetNodeColor(leafNodeList);
            rtBox.DeselectAll();
        }

        // 
        /*private string getRtf(string currentRtf)
        {
            var result = this.compiler.Parse(richTextBoxCtrl.Text);
            if (!result.HasErrors())
            {                
                rtBox.Rtf = richTextBoxCtrl.Rtf;
                SetColors(result);
                return rtBox.Rtf;
            }
            return currentRtf;
        }*/

        /*private void richTextBoxCtrl_TextChange(object sender, EventArgs e)
        {
            if (!changeFlag)
            {
                changeFlag = true;
                try
                {
                    var cursor = fastColoredTextBox1.SelectionStart;
                    fastColoredTextBox1.Rtf = this.getRtf(fastColoredTextBox1.Rtf);
                    richTextBoxCtrl.Select(cursor, 0);                    
                }
                catch
                {

                }
                changeFlag = false;
            }
            
        }*/
    }
}
